<?php
    header('content-type:text/html;charset="utf-8"');
    //定义统一返回格式
    $responseData = array("code" => 0,"message" => "");
    // var_dump($_POST);
    //取出传过来的数据
    $username = $_POST["username"];
    $goodname = $_POST["goodname"];
    $number = $_POST["number"];
    $day = $_POST["day"];
    $goodprice = $_POST["goodprice"];


    //验证
    if(!$number){
        $responseData["code"] = 1;
        $responseData["message"] = "租借数量不能为空";
        echo json_encode($responseData);
        exit;
    }
    if(!$day){
        $responseData["code"] = 2;
        $responseData["message"] = "租借天数不能为空";
        echo json_encode($responseData);
        exit;
    }


    // 1.连接数据库
    $link = mysqli_connect("localhost","root","root");

    // 2.判断是否连接成功
    if(!$link){
        $responseData['code'] = 3;
        $responseData['message'] = "数据库连接失败";
        // 返回到前台页面
        echo json_encode($responseData);
        exit; //结束后续操作
    }

    //3.设置字符集
    mysqli_set_charset($link,"utf8");

    //4.选择数据库
    mysqli_select_db($link,"租售系统");

    //5.准备sql语句将数据插入数据库

    $sql = "INSERT INTO rent(username,goodname,number,day,goodprice) VALUE
    ('{$username}','{$goodname}','{$number}','{$day}','{$goodprice}')";


    //6.再次发送sql
    $res = mysqli_query($link,$sql);

    //返回布尔值
    if(!$res){
        //添加失败
        $responseData["code"] = 4;
        $responseData["message"] = "提交失败了";
        echo json_encode($responseData);
        exit;
    }else{
        //添加成功
        $responseData["code"] = 0;
        $responseData["message"] = "提交成功";
        echo json_encode($responseData);
    }

    //8.关闭数据库
    mysqli_close($link);
?>